import axios from 'axios';
import { serverUrl } from '@/utils/components.js';
import axiosMiniprogramAdapter from 'axios-miniprogram-adapter';//适配器
axios.defaults.adapter = axiosMiniprogramAdapter;
const request = axios.create({
    baseURL: serverUrl, 
    timeout: 10000
});

// 添加请求拦截器
request.interceptors.request.use(
    (config) => {
        const userInfo = uni.getStorageSync('userInfo'); 
        if (userInfo) {
            config.headers.Authorization = `Bearer ${userInfo.token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
request.interceptors.response.use(
    (response) => {
        if (response.status === 200) {
            return response.data;
        } else {
            return Promise.reject(new Error(`请求失败，状态码: ${response.status}`));
        }
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default request;